package ua.com.minus1.lookbattle;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewFlipper;
import ua.com.minus1.lookbattle.models.CommonResult;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.utils.AppPreferences;

/**
 * Created with IntelliJ IDEA.
 * User: Denis
 * Date: 06.10.12
 * Time: 8:52
 * To change this template use File | Settings | File Templates.
 */
public class LoginFragment extends Fragment implements View.OnClickListener, AlertDialogFragment.Callbacks {

    private final int LOGIN_OK = 0;
    private final int LOGIN_EMAIL_EXISTS = 26;

    private ViewFlipper mViewFlipper;
    private EditText mEmailEdit;
    private EditText mUsernameEdit;
    private TextView mSendCodeEmailText;
    private EditText mCodeEdit;

    private HttpManager mHttpManager;
    private AppPreferences mPreferences;
    private String mUuid;
    private Callbacks mCallbacks;

    public static LoginFragment newInstance() {
        return new LoginFragment();
    }

    public interface Callbacks{
        void onRegister(boolean success);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewFlipper = (ViewFlipper) inflater.inflate(R.layout.fragment_login, container, false);
        setupViews();
        return mViewFlipper;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mPreferences = new AppPreferences(getActivity());
        mUuid = mPreferences.getUUID();
        mHttpManager = new HttpManager(getActivity());

        mCallbacks = (Callbacks) getActivity();

    }

    private void setupViews() {
        mEmailEdit = (EditText) mViewFlipper.findViewById(R.id.loginEmail);
        mUsernameEdit = (EditText) mViewFlipper.findViewById(R.id.loginUsername);
        mSendCodeEmailText = (TextView) mViewFlipper.findViewById(R.id.sendCodeEmailText);
        mCodeEdit = (EditText) mViewFlipper.findViewById(R.id.loginCode);

        Button[] btns = new Button[6];
        btns[0] = (Button) mViewFlipper.findViewById(R.id.loginRegisterBtn);
        btns[1] = (Button) mViewFlipper.findViewById(R.id.loginCancelRegisterBtn);
        btns[2] = (Button) mViewFlipper.findViewById(R.id.loginCodeSendBtn);
        btns[3] = (Button) mViewFlipper.findViewById(R.id.loginCancelCodeSendBtn);
        btns[4] = (Button) mViewFlipper.findViewById(R.id.loginCodeRegisterBtn);
        btns[5] = (Button) mViewFlipper.findViewById(R.id.loginCancelCodeRegisterBtn);

        for (Button btn : btns) {
            btn.setOnClickListener(this);
        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.loginRegisterBtn:
                register();
                break;
            case R.id.loginCancelRegisterBtn:
                mCallbacks.onRegister(false);
                break;
            case R.id.loginCodeSendBtn:
                sendCode();
                break;
            case R.id.loginCancelCodeSendBtn:
                reset();
                break;
            case R.id.loginCodeRegisterBtn:
                confirmCode();
                break;
            case R.id.loginCancelCodeRegisterBtn:
                reset();
                break;
        }
    }

    public void register() {
        mHttpManager.loadClass(URLManager.getRegisterURL(mUuid, mEmailEdit.getText().toString(), mUsernameEdit.getText().toString()), CommonResult.class, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                Log.i(LoginFragment.class.getName(), "Registration result: " + result.toString());

                switch (result.status) {
                    case LOGIN_OK:
                        mCallbacks.onRegister(true);
                        break;
                    case LOGIN_EMAIL_EXISTS:
                        mSendCodeEmailText.setText(mEmailEdit.getText());
                        mViewFlipper.setDisplayedChild(1);
                        break;
                }
            }
        });
    }

    public void sendCode() {
        mHttpManager.loadClass(URLManager.getSendCodeURL(mUuid, mEmailEdit.getText().toString()), CommonResult.class, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                Log.i(LoginFragment.class.getName(), "Send code result: " + result.toString());
                mViewFlipper.setDisplayedChild(2);
            }
        });
    }

    private void confirmCode() {
        Log.i(LoginFragment.class.getName(), "Confirm code url " + URLManager.getConfirmCode(mUuid, mCodeEdit.getText().toString()));
        mHttpManager.loadClass(URLManager.getConfirmCode(mUuid, mCodeEdit.getText().toString()), CommonResult.class, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                Log.i(LoginFragment.class.getName(), "Confirm code result: " + result.toString());
                if (result.status == 0) {
                    mPreferences.setClicks(result.clicks);
                    mCallbacks.onRegister(true);
                } else {
                    showIncorrectCodeDialog();
                }


            }
        });
    }

    private void showIncorrectCodeDialog() {
        AlertDialogFragment fragment = AlertDialogFragment.newInstance("Wrong code",
                "This is wrong code please try again",
                "Try again",
                "Cancel");

        fragment.show(getFragmentManager(), "incorrect_code");
    }

    public void onDialogDismiss(boolean success) {
        if (success)
            reenterCode();
        else
            reset();
    }

    public void reenterCode() {
        mCodeEdit.setText("");
    }

    public void reset() {
        mEmailEdit.setText("");
        mUsernameEdit.setText("");
        mCodeEdit.setText("");
        mViewFlipper.setDisplayedChild(0);
    }
}
